package com.bjbn.controller;

import com.bjbn.entity.EsDeviceValueThs;
import com.bjbn.entity.EsDeviceValueLx;
import com.bjbn.service.ElasticsearchService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Elasticsearch数据查询控制器
 */
@Slf4j
@RestController
@RequestMapping("/es")
@Tag(name = "Elasticsearch数据查询", description = "Elasticsearch数据查询相关接口")
public class ElasticsearchController {

    @Autowired
    private ElasticsearchService elasticsearchService;

    /**
     * 查询温湿度传感器数据
     * 
     * @param deviceNum 设备编号
     * @param startTime 开始时间（格式：yyyy-MM-dd HH:mm:ss）
     * @param endTime 结束时间（格式：yyyy-MM-dd HH:mm:ss）
     * @return 查询结果
     */
    @Operation(summary = "查询温湿度传感器数据", description = "根据设备编号和时间范围查询温湿度传感器数据")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "500", description = "查询失败")
    })
    @GetMapping("/ths/{deviceNum}")
    public Map<String, Object> queryThsData(
            @Parameter(description = "设备编号", required = true, example = "THS001")
            @PathVariable String deviceNum,
            @Parameter(description = "开始时间", example = "2024-01-01 00:00:00")
            @RequestParam(required = false) String startTime,
            @Parameter(description = "结束时间", example = "2024-01-31 23:59:59")
            @RequestParam(required = false) String endTime) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<EsDeviceValueThs> dataList = elasticsearchService.queryThsDataByDeviceNum(deviceNum, startTime, endTime);
            
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", dataList);
            result.put("count", dataList.size());
            
            log.info("查询温湿度传感器数据成功，设备编号：{}，返回{}条记录", deviceNum, dataList.size());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败：" + e.getMessage());
            result.put("data", null);
            result.put("count", 0);
            
            log.error("查询温湿度传感器数据失败，设备编号：{}", deviceNum, e);
        }
        
        return result;
    }

    /**
     * 查询照度传感器数据
     * 
     * @param deviceNum 设备编号
     * @param startTime 开始时间（格式：yyyy-MM-dd HH:mm:ss）
     * @param endTime 结束时间（格式：yyyy-MM-dd HH:mm:ss）
     * @return 查询结果
     */
    @Operation(summary = "查询照度传感器数据", description = "根据设备编号和时间范围查询照度传感器数据")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "500", description = "查询失败")
    })
    @GetMapping("/lx/{deviceNum}")
    public Map<String, Object> queryLxData(
            @Parameter(description = "设备编号", required = true, example = "LX001")
            @PathVariable String deviceNum,
            @Parameter(description = "开始时间", example = "2024-01-01 00:00:00")
            @RequestParam(required = false) String startTime,
            @Parameter(description = "结束时间", example = "2024-01-31 23:59:59")
            @RequestParam(required = false) String endTime) {
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<EsDeviceValueLx> dataList = elasticsearchService.queryLxDataByDeviceNum(deviceNum, startTime, endTime);
            
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", dataList);
            result.put("count", dataList.size());
            
            log.info("查询照度传感器数据成功，设备编号：{}，返回{}条记录", deviceNum, dataList.size());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败：" + e.getMessage());
            result.put("data", null);
            result.put("count", 0);
            
            log.error("查询照度传感器数据失败，设备编号：{}", deviceNum, e);
        }
        
        return result;
    }

    /**
     * 健康检查接口
     * 
     * @return 健康状态
     */
    @Operation(summary = "Elasticsearch健康检查", description = "检查Elasticsearch连接状态和服务健康情况")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "检查完成"),
            @ApiResponse(responseCode = "500", description = "检查失败")
    })
    @GetMapping("/health")
    public Map<String, Object> health() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 尝试查询一条测试数据来验证ES连接
            List<EsDeviceValueThs> testData = elasticsearchService.queryThsDataByDeviceNum("test", null, null);
            
            result.put("success", true);
            result.put("message", "Elasticsearch连接正常");
            result.put("status", "UP");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "Elasticsearch连接异常：" + e.getMessage());
            result.put("status", "DOWN");
            
            log.error("Elasticsearch健康检查失败", e);
        }
        
        return result;
    }
} 